package middleware

import (
	"gin-demo/common"
	"gin-demo/model"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {
		//获取请求header中的的authorization
		tokenString := context.GetHeader("Authorization")
		log.Println(tokenString)
		//验证格式
		if tokenString ==""||!strings.HasPrefix(tokenString,"Bearer"){
			log.Println("header中没有Bearer")
			context.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"权限不足"})
			context.Abort()
			return
		}
		tokenString = tokenString[7:]
		//解析token
		token,claims,err := common.ParseToken(tokenString)
		if err!=nil||!token.Valid{
			log.Println("解析失败")
			context.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"解析token失败"})
			context.Abort()
			return
		}
		//通过后获取claims中的userid,查询数据库是否存在
		userId := claims.UserId
		DB := common.InitDB()
		var user model.User
		DB.First(&user,userId)
		//用户不存在
		if user.ID==0{
			context.JSON(http.StatusUnauthorized,gin.H{"code":401,"msg":"用户不存在"})
			context.Abort()
			return
		}
		//用户存在,将user信息写入context，供后面的服务使用
		context.Set("user",user)
		context.Next()
	}
}
